import { getPurchase, postPurchase } from '@/api/purchase'

export default {
  name: "Purchase",
  components: {},
  props: [],
  data() {
    return {
      formData: {
        field101: undefined,
        field104: undefined
      },
      rules: {
        field101: [{
          required: true,
          message: 'SKU不能为空',
          trigger: 'blur'
        }],
        field104: [{
          required: true,
          type: 'array',
          message: '生效时间不能为空',
          trigger: 'change'
        }],
      },
    }
  },
  computed: {},
  watch: {},
  created() {
    this.init()
  },
  mounted() {},
  methods: {
    init() {
      getPurchase().then(res => {
        let str = ''
        res.items.forEach(item => {
          str += item.id + '=' + item.qty + ','
        })
        if(str.length > 0){
          str = str.substr(0, str.length - 1)
        }
        let formData = {
          field101: str,
          field104: [
            res.started_at,
            res.ended_at
          ]
        }
        this.formData = formData
      })
    },
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        // TODO 提交表单
        const formData = this.formData
        postPurchase({
          sku: formData.field101,
          started_at: formData.field104[0],
          ended_at: formData.field104[1]
        }).then(res => {
          this.init()
        })
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
  }
}


